import 'dart:io';
import 'dart:math';

import 'package:camera/camera.dart';
import 'package:flutter/material.dart';
import 'package:flutter_2/providers/CameraProvider.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:provider/provider.dart';

class CameraPage extends StatelessWidget {
  const CameraPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Theme.of(context).primaryColor,
      body: MultiProvider(
        providers: [ChangeNotifierProvider(create: (_) => CameraProvider())],
        child: CameraMain(),
      ),
      bottomNavigationBar: BottomAppBar(),
    );
  }
}

//
class AnimVideoButton extends StatefulWidget {
  const AnimVideoButton(
      {Key? key,
      required this.outWidth,
      required this.innerWidth,
      required this.provider,
      required this.rpx})
      : super(key: key);
  final double outWidth;
  final double innerWidth;
  final double rpx;
  final CameraProvider provider;

  @override
  State<AnimVideoButton> createState() => _AnimVideoButtonState();
}

class _AnimVideoButtonState extends State<AnimVideoButton>
    with TickerProviderStateMixin {
  late Animation<double> animation;
  late AnimationController controller;

  late double outWidth;
  late double innerWidth;
  late double outBorder;
  late double rpx;
  late double maxBorder;
  late bool ifRecording;
  late CameraProvider provider;
  double curBorder = 0;

  @override
  void dispose() {
    // TODO: implement dispose
    controller.dispose();
    super.dispose();
  }

  //录制视频动画
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    ifRecording = true;
    provider = widget.provider;
    outWidth = widget.outWidth;
    innerWidth = widget.innerWidth;
    rpx = widget.rpx;
    outBorder = 5 * rpx;
    maxBorder = (outWidth - innerWidth) / 2 - 10 * rpx;
    curBorder = outBorder;
    controller =
        AnimationController(duration: Duration(milliseconds: 500), vsync: this);
    animation =
        Tween<double>(begin: outBorder, end: maxBorder).animate(controller)
          ..addListener(() {
            setState(() {
              curBorder = animation.value;
            });
          });
    controller.repeat(reverse: true);
  }

  pauseRecording() {
    controller.stop();
    provider.cameraController!.pauseVideoRecording();
    setState(() {
      ifRecording = false;
    });
  }

  resumeRecording() {
    controller.repeat(reverse: true);
    provider.cameraController!.resumeVideoRecording();
    setState(() {
      ifRecording = true;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      width: outWidth,
      height: outWidth,
      decoration: BoxDecoration(
          shape: BoxShape.circle,
          color: Colors.transparent,
          border: Border.all(
              width: curBorder, color: Color.fromARGB(128, 219, 48, 85))),
      child: Container(
        child: !ifRecording
            ? IconButton(
                padding: EdgeInsets.all(0),
                icon: Icon(
                  Icons.play_arrow,
                  size: innerWidth,
                  color: Color.fromARGB(255, 219, 48, 85),
                ),
                onPressed: () {
                  resumeRecording();
                },
              )
            : IconButton(
                padding: EdgeInsets.all(0),
                icon: Icon(
                  Icons.pause,
                  size: innerWidth,
                  color: Color.fromARGB(255, 219, 48, 85),
                ),
                onPressed: () {
                  pauseRecording();
                },
              ),
      ),
    );
  }
}

//底部滚动组件
class ScrollBottomBar extends StatefulWidget {
  const ScrollBottomBar({
    Key? key,
    required this.rpx,
  }) : super(key: key);
  final double rpx;

  @override
  State<ScrollBottomBar> createState() => _ScrollBottomBarState();
}

class _ScrollBottomBarState extends State<ScrollBottomBar> {
  late double rpx;
  late double eachWidth;
  late double eachSide;
  List<String> items = [];
  late ScrollController controller;
  double startX = 0;
  double finalX = 0;

  late double minValue;
  late double maxValue;
  late double curX;
  late int curIndex;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    rpx = widget.rpx;
    eachWidth = 130 * rpx;
    eachSide = (750 - eachWidth / rpx) / 2 * rpx;
    curIndex = 2;
    minValue = 0;

    items = ['拍照', '拍15秒', '拍60秒', '影集', '开直播'];
    maxValue = (items.length - 1) * eachWidth;
    curX = curIndex * eachWidth;
    controller = ScrollController(initialScrollOffset: curX);
  }

  moveToItem(index) {
    curX = index * eachWidth;
    controller.animateTo(curX,
        duration: Duration(milliseconds: 200), curve: Curves.linear);
    setState(() {
      curX = curX;
      curIndex = index;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Listener(
          onPointerDown: ((event) {
            setState(() {
              startX = event.position.dx;
            });
          }),
          onPointerMove: ((event) {
            double moveValue = event.position.dx;
            double moved = startX - moveValue;
            double afterMoved = min(max(curX + moved, minValue), maxValue);
            setState(() {
              curX = afterMoved;
              startX = event.position.dx;
            });
          }),
          onPointerUp: ((event) {
            int index = 0;
            double finalPosition = curX + eachWidth / 2;
            index = (finalPosition / eachWidth).floor();
            moveToItem(index);
          }),
          child: Container(
            width: 750 * rpx,
            height: 100 * rpx,
            child: SingleChildScrollView(
              scrollDirection: Axis.horizontal,
              controller: controller,
              child: Container(
                child: Row(
                  children: [
                    SizedBox(
                      width: eachSide,
                    ),
                    Row(
                        children: List.generate(items.length, (index) {
                      return Container(
                        width: eachWidth,
                        child: FlatButton(
                          padding: EdgeInsets.all(0),
                          child: Text(
                            items[index],
                            style: TextStyle(
                                color: curIndex == index
                                    ? Colors.white
                                    : Colors.white.withOpacity(.5)),
                          ),
                          onPressed: () {
                            moveToItem(index);
                          },
                        ),
                      );
                    })),
                    SizedBox(
                      width: eachSide,
                    ),
                  ],
                ),
              ),
            ),
          ),
        ),
        Center(
          child: Container(
            decoration:
                BoxDecoration(shape: BoxShape.circle, color: Colors.white),
            width: 8 * rpx,
            height: 8 * rpx,
          ),
        )
      ],
    );
  }
}

//拍照 //录制
class CircleTakePhoto extends StatelessWidget {
  const CircleTakePhoto(
      {Key? key, required this.outBox, required this.innerBox})
      : super(key: key);
  final double outBox;
  final double innerBox;
  @override
  Widget build(BuildContext context) {
    double rpx = MediaQuery.of(context).size.width / 750;
    CameraProvider provider = Provider.of<CameraProvider>(context);

    // double outBox=160*rpx;
    // double innerBox=130*rpx;
    return Container(
      width: outBox,
      height: outBox,
      padding: EdgeInsets.all(10 * rpx),
      decoration: BoxDecoration(
        color: Colors.transparent,
        borderRadius: BorderRadius.circular(90 * rpx),
        border: Border.all(
            width: 10 * rpx, color: Color.fromARGB(128, 219, 48, 85)),
      ),
      child: FlatButton(
          padding: EdgeInsets.all(0),
          onPressed: () async {
            provider.changeFileName('png');
            XFile file = await provider.cameraController!.takePicture();
            await file.saveTo(provider.fileName);
            print("path2 => ${provider.fileName}");
            final result = await ImageGallerySaver.saveFile(provider.fileName);
            print("result => ${result}");
            File(provider.fileName).deleteSync();
            // provider.changeFileName('png');
            // print(provider.fileName);
            // await provider.cameraController
            //     .takePicture(provider.fileName)
            //     .then((_) {
            //   // Navigator.push(context, MaterialPageRoute(fullscreenDialog: true,builder: (_){
            //   //   return Image.file(File(provider.fileName) );
            //   // }));
            //   ImagePickerSaver.saveFile(
            //       fileData: File(provider.fileName).readAsBytesSync());
            // });
            // provider.changeFileName('mp4');
            // provider.cameraController?.startVideoRecording();
            // provider.changePhotoWidget();
          },
          child: Container(
            width: innerBox,
            height: innerBox,
            alignment: Alignment.center,
            decoration: BoxDecoration(
                color: Color.fromARGB(255, 219, 48, 85),
                borderRadius: BorderRadius.circular(75 * rpx)),
          )),
    );
  }
}

//从provider 拿到就statelss
class CameraMain extends StatelessWidget {
  const CameraMain({Key? key});

  @override
  Widget build(BuildContext context) {
    CameraProvider provider = Provider.of<CameraProvider>(context);
    double rpx = MediaQuery.of(context).size.width / 750;
    double toTop = 100 * rpx;
    double outBox = 170 * rpx;
    double innerBox = 130 * rpx;

    if (provider.cameraController == null) {
      return Container(
        child: Center(child: CircularProgressIndicator()),
      );
    }
    // _controller 必须后置初始化
    var _controller = provider.cameraController;
    var _cameras = provider.cameras;
    bool ifMakeVideo = provider.ifMakeVideo;
    return _controller!.value.isInitialized
        ? Stack(children: <Widget>[
            // Camera.open(cameraId),
            CameraPreview(_controller),
            Positioned(
              //顶部关闭按钮
              top: toTop,
              left: 30 * rpx,
              child: IconButton(
                icon: Icon(
                  Icons.close,
                  color: Colors.white,
                  size: 60 * rpx,
                ),
                onPressed: () {
                  Navigator.pop(context);
                },
              ),
            ),
            Positioned(
              //选择音乐
              top: toTop,
              left: 250 * rpx,
              child: Container(
                width: 250 * rpx,
                child: FlatButton(
                  onPressed: () {},
                  child: Row(
                    children: <Widget>[
                      Icon(
                        Icons.music_note,
                        color: Colors.white,
                      ),
                      SizedBox(
                        width: 10 * rpx,
                      ),
                      Text(
                        "选择音乐",
                        style: TextStyle(color: Colors.white),
                      ),
                    ],
                  ),
                ),
              ),
            ),
            Positioned(
              //拍照按钮
              bottom: 120 * rpx,
              // left: (750*rpx-outBox)/2,
              child: Container(
                  width: 750 * rpx,
                  child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceAround,
                      children: [
                        ifMakeVideo
                            ? Container(
                                width: 60 * rpx,
                              )
                            : IconWithText(
                                icon: Icon(
                                  Icons.search,
                                  color: Colors.white,
                                ),
                                text: "道具"),
                        ifMakeVideo
                            ? AnimVideoButton(
                                rpx: rpx,
                                outWidth: outBox,
                                innerWidth: innerBox - 40,
                                provider: provider,
                              )
                            : CircleTakePhoto(
                                outBox: outBox,
                                innerBox: innerBox,
                              ),
                        ifMakeVideo
                            ? IconButton(
                                padding: EdgeInsets.all(0),
                                icon: Icon(
                                  Icons.check_circle,
                                  size: 60 * rpx,
                                ),
                                onPressed: () async {
                                  provider.cameraController!
                                      .stopVideoRecording();
                                  await ImageGallerySaver.saveFile(
                                      provider.fileName);
                                  File(provider.fileName).delete();
                                },
                              )
                            : IconWithText(
                                icon: Icon(
                                  Icons.search,
                                  color: Colors.white,
                                ),
                                text: "道具"),
                      ])),
            ),
            Positioned(
              bottom: 40 * rpx,
              child: ScrollBottomBar(rpx: rpx),
            ),
            Positioned(
              right: 30 * rpx,
              top: 80 * rpx,
              child: IconButton(
                icon: Icon(Icons.camera_front),
                onPressed: () {
                  provider.changeCamera();
                },
              ),
            )
          ])
        : Container();
  }
}

class IconWithText extends StatelessWidget {
  const IconWithText({Key? key, required this.icon, required this.text})
      : super(key: key);
  final Icon icon;
  final String text;
  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        icon,
        Text(
          text,
          style: TextStyle(color: Colors.white),
        )
      ],
    );
  }
}
